package com.li.core.service.system.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.li.configserve.domain.gloabreturn.MyInfo;
import com.li.configserve.domain.gloabreturn.PageInfoVO;
import com.li.configserve.domain.gloabreturn.ResponseInfo;
import com.li.configserve.domain.gloabreturn.ResultEnum;
import com.li.core.domain.common.CustomParam;
import com.li.core.domain.system.User;
import com.li.core.domain.system.UserExample;
import com.li.core.mapper.system.UserMapper;
import com.li.core.service.system.UserService;
import com.li.toolkit.constant.NumConst;
import com.li.toolkit.utils.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 2021/12/14 20:35
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户分页接口
     *
     * @param pageParam
     * @return
     */
    @Override
    public PageInfoVO<User> listUserPage(CustomParam pageParam) {
        PageInfoVO<User> pageInfoVO = new PageInfoVO<>();
        pageInfoVO.setPageNumber(pageParam.getPageNumber());
        pageInfoVO.setPageSize(pageParam.getPageSize());
        PageHelper.startPage(pageParam.getPageNumber(), pageParam.getPageSize());
        List<User> list;
        if (!pageParam.getQueryForm().isEmpty()) {
            User user = MapUtils.mapToObject(pageParam.getQueryForm(), User.class);
            list = userMapper.listUser(user);
        } else {
            list = userMapper.selectByExample(new UserExample());
        }
        pageInfoVO.setData(list);
        pageInfoVO.setTotal(list.size());
        pageInfoVO.setCode(ResultEnum.SUCCESS.getCode());
        return pageInfoVO;
    }

    /**
     * 删除用户
     *
     * @param ids
     * @return
     */
    @Override
    public ResponseInfo<MyInfo> deleteUser(List<Integer> ids) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(ids);
        userMapper.deleteByExample(example);
        return ResponseInfo.success(NumConst.TWO_HUNDRED, "删除成功！");
    }

    /**
     * 新增修改
     *
     * @param paramMap
     * @return
     */
    @Override
    public ResponseInfo<MyInfo> addOrEditUser(Map<String, String> paramMap) {
        User user = JSON.parseObject(JSON.toJSONString(paramMap, SerializerFeature.WriteMapNullValue), User.class);
        if (user.getId() == null) {
            userMapper.insert(user);
        } else {
            userMapper.updateByPrimaryKey(user);
        }
        String message = Objects.isNull(user.getId()) ? "保存成功！" : "编辑成功！";
        return ResponseInfo.success(200, message);
    }
}
